package com.allwees.bs.module.oms.event.listener;

import com.allwees.bs.module.oms.dao.OrderDao;
import com.allwees.bs.module.oms.dao.OrderItemDao;
import com.allwees.bs.module.oms.dao.OrderSkuSnapDao;
import com.allwees.bs.module.oms.event.OrderShippedEvent;
import com.allwees.bs.module.ums.service.DeviceService;
import com.allwees.sender.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 事件：订单发货成功
 *
 * @author yangylsky
 *
 */
@Slf4j
@Component
public class OrderShippedListener {
	private final static String LINK = "AccountOrderDetailPage";

	private final static String NOTIFY_TITLE = "Order No. #{orderNo} shipped";
	private final static String NOTIFY_CONTENT = "The items you purchased were shipped #{shippingAt}, Will arrive in 15-30 days. Happy shopping!";

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private OrderItemDao orderItemDao;

	@Autowired
	private OrderSkuSnapDao orderSkuSnapDao;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private MessageSender messageSender;

	@Async
	@EventListener
	@Transactional
	public void on(OrderShippedEvent event) {
//		String orderUuid = (String) event.getSource();
//
//		Order order = orderDao.findByUuid(orderUuid);
//		if (order == null) {
//			return;
//		}

//		Device device = deviceService.findByUserUuid(order.getUserUuid());

//		String jpushId = device != null ? device.getJpushId() : null;
//		send(jpushId, order.getUserUuid(), order.getUuid(), order.getNo(), order.getShippingAt(), mainPhoto(orderUuid));
	}

//	private void send(String jpushId, String userUuid, String orderUuid, String orderNo, Date shippingAt, String mainPhoto) {
//		String title = NOTIFY_TITLE.replace("#{orderNo}", orderNo);
//		String content = NOTIFY_CONTENT.replace("#{shippingAt}", DateUtil.formatDate(shippingAt, DateUtil.SLASH_DATE_FORMAT));
//
//		if (StringUtils.isNotBlank(jpushId)) {
//			AppSender.push(jpushId, title, content);
//		}
//		Map<String, String> params = new HashMap<>();
//		params.put("orderUuid", orderUuid);
//		messageSender.send(userUuid, title, content, LINK, mainPhoto, params);
//	}
//
//	private String mainPhoto(String orderUuid) {
//		List<OrderItem> orderItems = orderItemDao.selectListByOrderUuid(orderUuid);
//		if(CollectionUtils.isEmpty(orderItems)){
//			return "";
//		}
//		OrderSkuSnap skuSnap = orderSkuSnapDao.findOne(orderUuid, orderItems.get(0).getSkuUuid());
//		return skuSnap != null ? skuSnap.getProductPhoto() : "";
//	}
}
